package com.example.practice.controller;

import com.example.practice.entity.CommunityPhoto;
import com.example.practice.repository.CommunityPhotoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/community")
public class CommunityPhotoController {

    @Autowired
    private CommunityPhotoRepository communityPhotoRepository;
    
    // 照片存储目录
    private final String UPLOAD_DIR = "src/main/resources/static/uploads/";

    /**
     * 获取所有社区照片
     * @return 照片列表
     */
    @GetMapping("/photos")
    public ResponseEntity<List<CommunityPhoto>> getAllPhotos() {
        try {
            List<CommunityPhoto> photos = communityPhotoRepository.findAllByOrderByCreatedAtDesc();
            return ResponseEntity.ok(photos);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取用户上传的照片
     * @param username 用户名
     * @return 用户照片列表
     */
    @GetMapping("/photos/user")
    public ResponseEntity<List<CommunityPhoto>> getUserPhotos(@RequestParam String username) {
        try {
            List<CommunityPhoto> photos = communityPhotoRepository.findByUsername(username);
            return ResponseEntity.ok(photos);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取热门照片（按点赞数排序）
     * @return 热门照片列表
     */
    @GetMapping("/photos/popular")
    public ResponseEntity<List<CommunityPhoto>> getPopularPhotos() {
        try {
            List<CommunityPhoto> photos = communityPhotoRepository.findTop10ByOrderByLikesCountDesc();
            return ResponseEntity.ok(photos);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 上传照片
     * @param username 用户名
     * @param file 照片文件
     * @param description 照片描述
     * @return 上传结果
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadPhoto(
            @RequestParam String username,
            @RequestParam("file") MultipartFile file,
            @RequestParam(required = false) String description) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择要上传的照片");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                response.put("success", false);
                response.put("message", "只能上传图片文件");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 创建上传目录
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            // 生成唯一文件名
            String originalFileName = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFileName != null && originalFileName.contains(".")) {
                fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            }
            String uniqueFileName = UUID.randomUUID().toString() + fileExtension;
            
            // 保存文件
            Path filePath = Paths.get(UPLOAD_DIR + uniqueFileName);
            Files.copy(file.getInputStream(), filePath);
            
            // 构建照片URL
            String photoUrl = "/uploads/" + uniqueFileName;
            
            // 创建照片记录
            CommunityPhoto photo = new CommunityPhoto(username, 1L, photoUrl, description); // 暂时使用默认用户ID
            communityPhotoRepository.save(photo);
            
            response.put("success", true);
            response.put("message", "照片上传成功");
            response.put("photoUrl", photoUrl);
            response.put("photoId", photo.getId());
            
            return ResponseEntity.ok(response);
            
        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "文件保存失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "上传失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 删除照片
     * @param photoId 照片ID
     * @param username 用户名
     * @return 删除结果
     */
    @DeleteMapping("/photos/{photoId}")
    public ResponseEntity<Map<String, Object>> deletePhoto(
            @PathVariable Long photoId,
            @RequestParam String username) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            CommunityPhoto photo = communityPhotoRepository.findByIdAndUsername(photoId, username);
            if (photo == null) {
                response.put("success", false);
                response.put("message", "照片不存在或无权删除");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 删除文件
            String photoUrl = photo.getPhotoUrl();
            if (photoUrl != null && photoUrl.startsWith("/uploads/")) {
                String fileName = photoUrl.substring("/uploads/".length());
                Path filePath = Paths.get(UPLOAD_DIR + fileName);
                Files.deleteIfExists(filePath);
            }
            
            // 删除数据库记录
            communityPhotoRepository.delete(photo);
            
            response.put("success", true);
            response.put("message", "照片删除成功");
            return ResponseEntity.ok(response);
            
        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "文件删除失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 点赞照片
     * @param photoId 照片ID
     * @return 点赞结果
     */
    @PostMapping("/photos/{photoId}/like")
    public ResponseEntity<Map<String, Object>> likePhoto(@PathVariable Long photoId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            CommunityPhoto photo = communityPhotoRepository.findById(photoId).orElse(null);
            if (photo == null) {
                response.put("success", false);
                response.put("message", "照片不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            photo.incrementLikes();
            communityPhotoRepository.save(photo);
            
            response.put("success", true);
            response.put("message", "点赞成功");
            response.put("likesCount", photo.getLikesCount());
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "点赞失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 取消点赞照片
     * @param photoId 照片ID
     * @return 取消点赞结果
     */
    @PostMapping("/photos/{photoId}/unlike")
    public ResponseEntity<Map<String, Object>> unlikePhoto(@PathVariable Long photoId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            CommunityPhoto photo = communityPhotoRepository.findById(photoId).orElse(null);
            if (photo == null) {
                response.put("success", false);
                response.put("message", "照片不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            photo.decrementLikes();
            communityPhotoRepository.save(photo);
            
            response.put("success", true);
            response.put("message", "取消点赞成功");
            response.put("likesCount", photo.getLikesCount());
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "取消点赞失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}